import { Button, List, DatePicker, NavBar, Popup, Toast, Dialog } from "antd-mobile";
import classNames from "classnames";
import styles from "./index.module.scss";
import { getUserProfile, updateUserPhoto, updateUserProfile } from "@/store/actions/profile";
import useInitialState from "@/utils/use-initial-state";
import { useRef, useState } from "react";
import EditInput from "@/components/EditInput";
import { useDispatch } from "react-redux";
import EditList from "@/components/EditList";
import dayjs from "dayjs";
import { useHistory } from "react-router-dom";
import { logout } from "@/store/actions/login";
const Item = List.Item;
type InputState = {
  visible: boolean;
  type: "" | "name" | "intro";
};
type ListState = {
  visible: boolean;
  type: "" | "gender" | "photo";
};
const ProfileEdit = () => {
  //通过自定义hook直接拿到状态
  const { userProfile } = useInitialState(getUserProfile, "profile");
  const dispatch = useDispatch();
  const history = useHistory();

  //姓名简介修改======================================================
  const [showInput, setShowInput] = useState<InputState>({
    type: "",
    visible: false,
  });
  const hideName = () => {
    setShowInput((value) => {
      return {
        ...value,
        visible: false,
      };
    });
  };
  const onUpdate = async (key: string, value: string) => {
    if (key === "photo") {
      // 需要修改头像
      fileRef.current!.click();
      return;
    }
    await dispatch(updateUserProfile(key, value));
    Toast.show({
      icon: "success",
      content: "修改成功",
    });
    hideName();
    hideList();
  };

  //头像性别修改======================================================
  const [showList, setShowList] = useState<ListState>({
    visible: false,
    type: "",
  });

  const hideList = () => {
    setShowList({
      type: "",
      visible: false,
    });
  };
  // 头像文件上传=======================================================
  const fileRef = useRef<HTMLInputElement>(null);
  const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.files);
    // 获取选择的文件
    const file = e.target.files![0];
    // 上传这张图片，存放在formdata格式的对象中
    const fd = new FormData();
    fd.append("photo", file);
    // 发送请求
    await dispatch(updateUserPhoto(fd));
    Toast.show({
      icon: "success",
      content: "修改头像成功",
    });
    hideList();
  };
  // 更改生日============================================================================
  const [showBirthday, setShowBirthday] = useState(false);

  const onBirthdayShow = () => {
    setShowBirthday(true);
  };
  const onBirthdayHide = () => {
    setShowBirthday(false);
  };
  // 退出登录====================================================================
  const logoutFn = () => {
    Dialog.show({
      title: "温馨提示",
      content: "你确定要退出吗？",
      closeOnAction: true,
      actions: [
        [
          {
            key: "cancel",
            text: "取消",
            style: {
              color: "blue",
            },
          },
          {
            key: "confirm",
            text: "确定",
            danger: true,
            bold: true,
            onClick: () => {
              // 1. 清除token
              dispatch(logout());
              // 2. 跳转到登录
              history.push("/login");
              // 3. 给一个提示消息
              Toast.show({
                icon: "success",
                content: "退出成功",
              });
            },
          },
        ],
      ],
    });
  };
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            "--border-bottom": "1px solid #F0F0F0",
          }}
          onBack={() => history.go(-1)}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={userProfile?.photo} alt="" />
                </span>
              }
              arrow
              onClick={() =>
                setShowList({
                  visible: true,
                  type: "photo",
                })
              }
            >
              头像
            </Item>
            <Item
              arrow
              extra={userProfile?.name}
              onClick={() =>
                setShowInput({
                  visible: true,
                  type: "name",
                })
              }
            >
              昵称
            </Item>
            <Item
              arrow
              extra={<span className={classNames("intro", userProfile?.intro && "normal")}>{userProfile?.intro || "未填写"}</span>}
              onClick={() =>
                setShowInput({
                  visible: true,
                  type: "intro",
                })
              }
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item arrow onClick={() => setShowList({ visible: true, type: "gender" })} extra={userProfile?.gender === 0 ? "男" : "女"}>
              性别
            </Item>
            <Item arrow extra={userProfile?.birthday} onClick={onBirthdayShow}>
              生日
            </Item>
          </List>

          <DatePicker visible={false} value={new Date()} title="选择年月日" min={new Date(1900, 0, 1, 0, 0, 0)} max={new Date()} />
        </div>

        <div className="logout">
          <Button className="btn" onClick={logoutFn}>
            退出登录
          </Button>
        </div>
      </div>
      {/* 修改姓名跟简介 */}
      <Popup visible={showInput.visible} bodyStyle={{ height: "100%" }} position="right" destroyOnClose>
        <EditInput hideName={hideName} type={showInput.type} onUpdate={onUpdate}></EditInput>
      </Popup>
      {/* 修改头像跟性别 */}
      <Popup visible={showList.visible} destroyOnClose onMaskClick={hideList}>
        <EditList hideList={hideList} type={showList.type} onUpdate={onUpdate} />
      </Popup>
      <input type="file" onChange={onChangePhoto} hidden ref={fileRef} />
      <DatePicker
        visible={showBirthday}
        value={new Date(userProfile?.birthday)}
        onCancel={onBirthdayHide}
        title="选择年月日"
        min={new Date("1900-01-01")}
        max={new Date()}
        onConfirm={(val) => {
          onUpdate("birthday", dayjs(val).format("YYYY-MM-DD"));
        }}
      />
    </div>
  );
};

export default ProfileEdit;
